﻿$(() => {
    const loadDepartments = function () {
        return new Promise(resolve => {
            const userName = $('#UserName').val();
            const departmentEle = $('#Department').get(0);
            departmentEle.options.length = 0;
            if (userName.trim()) {
                abp.ajax({
                    type: 'GET',
                    url: `/api/user-groups?userName=${userName}`
                }).then((res) => {
                    if (res.code === 0) {
                        var data = res.data;
                        departmentEle.options.add(new Option('请选择一个用户组', ''));
                        if (data && data instanceof Array) {
                            data.forEach((item) => {
                                departmentEle.options.add(new Option(item.name, item.id));
                                if (item.isDefault) { // 显示默认科室
                                    departmentEle.value = item.id;
                                }
                            });
                            resolve(data);
                        }
                    }
                });
            }
        });
    };

    $('#UserName').on('blur', loadDepartments);

    $('#Department').on('click', function () {
        if ($('#Department').get(0).options.length === 1) {
            loadDepartments();
        }
    });
});